package com.example.demo.commons.exception;

import com.example.demo.commons.r.Codes;
import com.example.demo.commons.r.R;
import jakarta.validation.ConstraintViolationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {
    // 全局异常
    @ExceptionHandler(Throwable.class)
    public R globalExceptionHandler(Throwable e) {
        System.out.println("捕获到全局异常信息！！" + e);
        return R.fail(Codes.FAIL);
    }

    // 自定义异常,业务层
    @ExceptionHandler(ServiceException.class)
    public R serviceException(ServiceException e) {
        Codes codes = e.getCodes();
        return R.fail(codes);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R requestBodyParamException(MethodArgumentNotValidException e) {
        // Stream流
        List<String> error = e.getBindingResult().getAllErrors()
                .stream().map(objectError -> objectError.getDefaultMessage())
                .collect(Collectors.toList());
        return R.fail(Codes.RARAMS_ERROR, error);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public R paramsValidateException(ConstraintViolationException e) {
        List<String> message = e.getConstraintViolations().stream().map(constraintViolation -> constraintViolation.getMessage()).collect(Collectors.toList());
        return R.fail(Codes.RARAMS_ERROR, message);
    }
}
